package com.chery.media.ui.play.usb

import android.annotation.SuppressLint
import android.content.IntentFilter
import android.hardware.usb.UsbManager
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.Utils
import com.chery.media.contacts.ActionContacts
import com.chery.media.library.base.BaseViewModel
import com.chery.media.library.event.SingleLiveEvent
import com.chery.media.library.extend.toast
import com.chery.media.network.model.MusicBean
import com.chery.media.utils.LocalMusicHelper
import com.chery.media.utils.USBBroadcastReceiver

class UsbViewModel : BaseViewModel() {


    val usbMusicList = SingleLiveEvent<ArrayList<MusicBean>>()

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        initBroad()
    }

    /**
     * 初始化监听
     */
    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    fun initBroad(){
        val usbBroadcastReceiver = USBBroadcastReceiver()
        val usbDeviceStateFilter = IntentFilter()
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
        usbDeviceStateFilter.addAction(ActionContacts.ACTION_USB_PERMISSION)
        Utils.getApp().registerReceiver(usbBroadcastReceiver, usbDeviceStateFilter)
    }


    /**
     * 获取U盘音乐列表
     */
    fun getUsbMusicList() {
        launch {
            usbMusicList.value = LocalMusicHelper.getLocalMusics(Utils.getApp())
        }
    }
}